//
//  DMThinkingManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/8/7.
//

#import "DMThinkingManager.h"
#import <ThinkingSDK/ThinkingSDK.h>
#import "DMConfigReader.h"
#import "IMLogUtils.h"
#import "../AdStrategy/IMSDKStartupConfigManager.h"

#pragma mark - 常量定义

// 日志标签常量
static const IMLogTag kDMThinkingManagerTag = IMLogTagAPI;

// 关卡相关常量
static const NSInteger kLevelOffset = 100000;
static NSString * const kEventLevelEnter = @"w_level_enter";
static NSString * const kEventLevelStart = @"w_level_start";
static NSString * const kEventLevelWin = @"w_level_win";
static NSString * const kEventLevelFail = @"w_level_fail";
static NSString * const kEventLevelRevive = @"w_level_revive";
static NSString * const kEventLevelRetry = @"w_level_retry";
static NSString * const kEventLevelProp = @"w_level_prop";
static NSString * const kPropertyLevel = @"level";

// 时区常量
static NSString * const kTimeZoneGMT8 = @"GMT+0800";

// ThinkingData SDK 初始化标记，避免重复初始化
static BOOL kThinkingSDKStarted = NO;
// 广告事件前缀常量
static NSString * const kAdLoadEventPrefix = @"SDK_ad_fill_";   // 广告加载行为事件
static NSString * const kAdShowEventPrefix = @"SDK_ad_show_";   // 广告展示行为事件

#pragma mark - 私有接口

@interface DMThinkingManager()

/**
 * @brief 追踪关卡相关事件的通用方法
 * @param eventName 事件名称
 * @param level 关卡等级
 */
- (void)trackLevelEventWithEventName:(NSString *)eventName level:(NSInteger)level;

/**
 * @brief 配置时区校准
 */
- (void)configureTimeZone;

/**
 * @brief 配置第三方数据共享
 */
- (void)configureThirdPartySharing;

/**
 * @brief 配置自动追踪功能
 */
- (void)configureAutoTracking;

/**
 * @brief 记录配置信息日志
 */
- (void)logConfigurationInfo;

/**
 * @brief 检查广告行为上报是否启用
 * @return YES表示启用，NO表示禁用
 */
- (BOOL)isAdTrackEnabled;

/**
 * @brief 检查广告加载上报是否启用
 * @return YES表示启用，NO表示禁用
 */
- (BOOL)isAdLoadTrackEnabled;

/**
 * @brief 判断事件是否为广告加载行为事件（SDK_ad_fill_ 前缀）
 */
- (BOOL)isAdLoadEventKey:(NSString *)key;

/**
 * @brief 判断事件是否为广告展示行为事件（SDK_ad_show_ 前缀）
 */
- (BOOL)isAdShowEventKey:(NSString *)key;

@end

#pragma mark - 实现

@implementation DMThinkingManager
{
    TDAnalytics *instance;
}

#pragma mark - 单例管理

static DMThinkingManager *_ThinkingManager = nil;

+ (instancetype)shareThinkingManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _ThinkingManager = [[self alloc] init];
    });
    return _ThinkingManager;
}

+ (instancetype)sharedManager {
    return [self shareThinkingManager];
}

#pragma mark - SDK配置

- (void)thinkingConfig {
    if (kThinkingSDKStarted) {
        [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] ThinkingData SDK已初始化，跳过重复初始化"];
        return;
    }
    // 进入初始化并打印环境与标记
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 进入ThinkingData初始化，isDebug=%@, kThinkingSDKStarted=%@", [IMLogUtils isDebugEnvironment] ? @"YES" : @"NO", kThinkingSDKStarted ? @"YES" : @"NO"];
    
    // 读取TA配置
    DMTAConfig *taCfg = [[DMConfigReader sharedInstance] taConfig];
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 读取TA配置：app_id=%@, server_url=%@", taCfg.app_id ?: @"(null)", taCfg.server_url ?: @"(null)"];
    if (!taCfg || taCfg.app_id.length == 0 || taCfg.server_url.length == 0) {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] TA配置缺失或不合法，初始化失败。app_id=%@, server_url=%@", taCfg.app_id ?: @"(null)", taCfg.server_url ?: @"(null)"];
        return;
    }
    // 校验 server_url 合法性
    NSURL *serverURL = [NSURL URLWithString:taCfg.server_url];
    if (!serverURL || !serverURL.scheme || !serverURL.host) {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] server_url不合法，必须包含scheme和host。server_url=%@", taCfg.server_url];
        return;
    }
    // 检查 TDAnalytics 类是否可用
    Class tdAnalyticsClass = NSClassFromString(@"TDAnalytics");
    if (!tdAnalyticsClass) {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] TDAnalytics 类不存在，可能未正确集成 ThinkingSDK"];
        return;
    }
    
    // 构建TDConfig并初始化SDK
    TDConfig *tdConfig = [[TDConfig alloc] initWithAppId:taCfg.app_id serverUrl:taCfg.server_url];
#if DEBUG
    tdConfig.mode = TDModeDebug;
#else
    tdConfig.mode = TDModeNormal;
#endif
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] TDConfig 构建完成 (app_id=%@)", taCfg.app_id];
    tdConfig.defaultTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT+0800"];
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 设置默认时区：GMT+0800"];
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970]*1000;
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 校准时间 (ms)：%.0f", time];
    [TDAnalytics calibrateTime: time];
    
    // 启动 SDK，增加异常捕获日志
    @try {
        [TDAnalytics startAnalyticsWithConfig:tdConfig];
        kThinkingSDKStarted = YES;
        [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] ThinkingData SDK初始化完成，app_id=%@ 数数设备 ID:%@", taCfg.app_id, [TDAnalytics getDeviceId]];
    } @catch (NSException *exception) {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] ThinkingData SDK初始化异常：name=%@, reason=%@", exception.name, exception.reason];
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] 异常堆栈：%@", exception.callStackSymbols];
        return;
    }
    
    // 其他配置
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 开始配置第三方共享与日志等级、自动追踪"];
    [self configureThirdPartySharing];
    [self logConfigurationInfo];
    [self configureAutoTracking];
    [TDAnalytics setCustomerLibInfoWithLibName:@"iOS" libVersion:@"1.0"];
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 客户库信息设置完成：libName=iOS, libVersion=1.0"];
}

#pragma mark - 公共属性管理

- (void)thinkingSetSuperPropertiesJsonStr:(id)jsonStr
{
    if (!jsonStr)
    {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] Super properties cannot be nil"];
        return;
    }
    
    NSDictionary *dict;
    
    if ([jsonStr isKindOfClass:[NSDictionary class]])
    {
        dict = (NSDictionary *)jsonStr;
    }
    else if ([jsonStr isKindOfClass:[NSString class]])
    {
        NSData *jsonData = [(NSString *)jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        NSDictionary *temp = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        
        if (error)
        {
            [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] JSON解析失败: %@", error.localizedDescription];
            temp = nil;
        }
        
        if (temp)
        {
            dict = temp;
        }
    }
    
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 公共属性--%@", dict];
    if (dict)
    {
        [TDAnalytics setSuperProperties:dict];
        [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 公共属性设置成功"];
    }
}

#pragma mark - 事件追踪

- (void)thinkingTrackEventWithKey:(NSString *)key jsonStr:(id)jsonStr
{
    if (!key || key.length == 0)
    {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] Event key cannot be nil or empty"];
        return;
    }
    if (!jsonStr)
    {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] Event properties cannot be nil"];
        return;
    }
    // 仅按事件类别拦截：展示类与加载类分开判断
    if (![self isAdTrackEnabled] && [self isAdShowEventKey:key])
    {
        [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 广告展示行为上报已禁用，跳过展示类事件: %@", key];
        return;
    }
    if (![self isAdLoadTrackEnabled] && [self isAdLoadEventKey:key])
    {
        [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 广告加载行为上报已禁用，跳过加载类事件: %@", key];
        return;
    }
    NSDictionary *dict;
    if ([jsonStr isKindOfClass:[NSDictionary class]]) {
        dict = (NSDictionary *)jsonStr;
    } else if ([jsonStr isKindOfClass:[NSString class]]) {
        NSError *error;
        NSData *jsonData = [(NSString *)jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        dict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        if (error) {
            [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] JSON parsing failed: %@", error.localizedDescription];
            return;
        }
    } else {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] Invalid jsonStr type, expected NSDictionary or NSString"];
        return;
    }
    [TDAnalytics track:key properties:dict];
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 事件上报成功: %@", key];
}

- (void)thinkingTrackEventWithKey:(NSString *)key properties:(NSDictionary *)properties
{
    [self thinkingTrackEventWithKey:key jsonStr:properties];
}

#pragma mark - 用户属性管理

- (void)thinkingTrackUserPropertiesJsonStr:(id)jsonStr
{
    if (!jsonStr)
    {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] User properties cannot be nil"];
        return;
    }
    
    NSDictionary *dict = nil;
    
    if ([jsonStr isKindOfClass:[NSDictionary class]])
    {
        dict = (NSDictionary *)jsonStr;
    }
    else if ([jsonStr isKindOfClass:[NSString class]])
    {
        NSError *error = nil;
        NSData *jsonData = [(NSString *)jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *temp = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        if (error)
        {
            [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] JSON解析失败: %@", error.localizedDescription];
            temp = nil;
        }
        dict = temp;
    }
    else
    {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] Invalid user properties type, expected NSDictionary or NSString"];
        return;
    }
    
    if (!dict || dict.count == 0)
    {
        [IMLogUtils warning:kDMThinkingManagerTag format:@"[TA] 用户属性为空或解析失败，忽略设置"];
        return;
    }
    
    [TDAnalytics userSet:dict];
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 用户属性设置: %@", dict];
}

- (void)thinkingUser_setOnceWithKey:(NSString *)key value:(NSString *)value
{
    if (!key || key.length == 0)
    {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] User property key cannot be nil or empty"];
        return;
    }
    
    if (!value)
    {
        [IMLogUtils warning:kDMThinkingManagerTag format:@"[TA] User property value is nil, this will not set the property"];
        return;
    }
    
    [TDAnalytics userSetOnce:@{key: value}];
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 用户属性(一次)设置: %@=%@", key, value];
}

#pragma mark - 游戏关卡事件追踪

- (void)thinkingTrackLevelEnter:(NSInteger)level
{
    [self trackLevelEventWithEventName:kEventLevelEnter level:level];
}

- (void)thinkingTrackLevelStart:(NSInteger)level
{
    [self trackLevelEventWithEventName:kEventLevelStart level:level];
}

- (void)thinkingTrackLevelWin:(NSInteger)level
{
    [self trackLevelEventWithEventName:kEventLevelWin level:level];
}

- (void)thinkingTrackLevelFail:(NSInteger)level
{
    [self trackLevelEventWithEventName:kEventLevelFail level:level];
}

- (void)thinkingTrackLevelRevive:(NSInteger)level
{
    [self trackLevelEventWithEventName:kEventLevelRevive level:level];
}

- (void)thinkingTrackLevelRetry:(NSInteger)level
{
    [self trackLevelEventWithEventName:kEventLevelRetry level:level];
}

- (void)thinkingTrackLevelProp:(NSInteger)level
{
    [self trackLevelEventWithEventName:kEventLevelProp level:level];
}

#pragma mark - 私有方法

- (void)trackLevelEventWithEventName:(NSString *)eventName level:(NSInteger)level
{
    if (!eventName || eventName.length == 0)
    {
        [IMLogUtils error:kDMThinkingManagerTag format:@"[TA] Event name cannot be nil or empty"];
        return;
    }
    
    if (level < 0)
    {
        [IMLogUtils warning:kDMThinkingManagerTag format:@"[TA] Level %ld is negative, this might be unintended", level];
    }
    
    NSDictionary *dict = @{kPropertyLevel: [NSString stringWithFormat:@"%ld", level + kLevelOffset]};
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] 关卡事件：%@, level=%ld(偏移后=%ld)", eventName, (long)level, (long)(level + kLevelOffset)];
    [self thinkingTrackEventWithKey:eventName jsonStr:dict];
}

- (void)configureTimeZone
{
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];
    [TDAnalytics calibrateTime:timeInterval];
    [TDAnalytics calibrateTimeWithNtp:kTimeZoneGMT8];
}

- (void)configureThirdPartySharing
{
    if ([IMLogUtils isDebugEnvironment])
    {
        [TDAnalytics enableThirdPartySharing:TDThirdPartyTypeAdjust | TDThirdPartyTypeIronSource | TDThirdPartyTypeAppLovin];
    }
}

- (void)logConfigurationInfo
{
#if DEBUG
    [TDAnalytics enableLog:TDLoggingLevelDebug];
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] ThinkingData 日志等级：Debug"];
#else
    [TDAnalytics enableLog:TDLoggingLevelNone];
    [IMLogUtils info:kDMThinkingManagerTag format:@"[TA] ThinkingData 日志等级：None（Release）"];
#endif
}

- (void)configureAutoTracking
{
    [TDAnalytics enableAutoTrack:
        TDAutoTrackEventTypeAppStart |
        TDAutoTrackEventTypeAppEnd |
        TDAutoTrackEventTypeAppClick |
        TDAutoTrackEventTypeAppViewScreen |
        TDAutoTrackEventTypeAppViewCrash
    ];
}

- (BOOL)isAdTrackEnabled
{
    return [[IMSDKStartupConfigManager sharedManager] isAdTrackEnabled];
}

- (BOOL)isAdLoadTrackEnabled
{
    return [[IMSDKStartupConfigManager sharedManager] isAdLoadTrackEnabled];
}

- (BOOL)isAdLoadEventKey:(NSString *)key
{
    if (!key) { return NO; }
    return [key hasPrefix:kAdLoadEventPrefix];
}

- (BOOL)isAdShowEventKey:(NSString *)key
{
    if (!key) { return NO; }
    return [key hasPrefix:kAdShowEventPrefix];
}

@end
